欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

板凳——————————————————C++(9)

程序员文章站 2022-07-14 07:54:17
...

#include “SpreadsheetCell.cpp”
#include
#include
#include
#include <initializer_list>
#include
#include
// Professional c++ 4th Edition P 144-p153
class Foo{
public:
Foo(double value);
private:
double mValue;
};

Foo::Foo(double value) : mValue(value){
std::cout << "Foo::mValue = " << mValue << std::endl;
}

//class MyClass{
// public:
// MyClass (double value);
// private:
// double mValue; //先
// Foo mFoo; // 后
//};

class MyClass{
public:
MyClass (double value);
MyClass(char c) : MyClass(1.2) {}

private:
   Foo mFoo;      //  先          
   double mValue; //  后

};
// 按数据成员在类定义中的顺序 对数据成员进行初始化
MyClass::MyClass(double value) : mValue(value), mFoo(mValue){
std::cout << "MyClass::mValue = " << mValue << std::endl;
}

void printString(std::string inString){
std::cout << inString << std::endl;
}
//p 146
class EvenSequence{
public:
EvenSequence(std::initializer_list args){
if(args.size() % 2 != 0) {
throw std::invalid_argument("initializer_list should "
“contain even number of elements.”);
}
mSequence.reserve(args.size());
for (const auto& value : args){
mSequence.push_back(value);
}
}
void dump() const{
for(const auto& value : mSequence){
std::cout << value << ", ";
}
std::cout << std::endl;
}
private:
std::vector mSequence;
};

//void EvenSequence(std::initializer_list args){
// if(args.size() % 2 != 0){
// throw std::invalid_argument("initializer_list should "
// “contain even number of elements.”);
// }
// mSequence.assign(args);
//}

int main(){
MyClass instance(1.2);

std::string name = "heading one";
printString(name);

SpreadsheetCell myCell1(4);
SpreadsheetCell myCell2(myCell1);

EvenSequence p1 = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
p1.dump();

try{
    EvenSequence p2 = {1.0, 2.0, 3.0};
}catch (const std::invalid_argument& e){
    std::cout << e.what() << std::endl;
}

std::vector<std::string> myVec {"String 1", "String 2", "String 3"};
SpreadsheetCell myCell(5);
if(myCell.getValue() == 5){
    SpreadsheetCell anotherCell(6);
}
std::cout << "myCell: " << myCell.getValue() << std::endl;

SpreadsheetCell* cellPtr1 = new SpreadsheetCell(5);
SpreadsheetCell* cellPtr2 = new SpreadsheetCell(6);
std::cout << "cellPtr1: " << cellPtr1->getValue() << std::endl;
delete cellPtr1;
cellPtr1 = nullptr;
	
SpreadsheetCell  cell(4);
cell = cell;

SpreadsheetCell myCell3(5);
std::string s1;
s1 = myCell3.getString();

SpreadsheetCell myCell4(5);
std::string s2 = myCell4.getString();
return 0;

}
/*
[email protected]:~$ g++ -std=c++17 -o c17 c17.cpp
[email protected]:~$ ./c17
Foo::mValue = 1.2
MyClass::mValue = 1.2

//对myclass , 翻转mvalue 和 mfoo 数据成员的顺序
Foo::mValue = 2.07543e-317
MyClass::mValue = 1.2
heading one
1, 2, 3, 4, 5, 6,
initializer_list should contain even number of elements.
myCell: 5
cellPtr1: 5

*/