Bugfix:
FAILED: memberFunction.exe
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
这种是因为CLion的工程中只能有一个主函数,一种方法是删除其他程序的主函数入口,另一种方法是修改CMakeLists文件,为每个程序创建一个可运行文件,如下图所示。
1、数据结构
#include<iostream>
using namespace std;
void printInfo(struct Papers *paper); // 使用指向结构的指针来进行访问
//struct Papers {
// double price;
//};
typedef struct Papers {
double price;
} Papers; //别名Papers可与当做变量类型,推荐用法
int main() {
Papers paper;
paper.price = 50.0;
cout << paper.price << endl;
printInfo(&paper); //&paper为paper对象的地址
return 0;
};
void printInfo(struct Papers *paper) {
cout << "The paper' price is " << paper->price << endl;
}
// output:
50
The paper' price is 50
2、C++面向对象
#include<iostream>
using namespace std;
class Box{
public:
double length;
double get(void);
void set(double len);
};
double Box::get(void){
return length;
}
int main(){
Box a;
double len = 1.5;
a.length = len;
double length = a.length;
cout<<"Box lenght is "<<length<<endl;
return 0;
}
3、成员函数
// 类成员函数(membder function)
#include<iostream>
using namespace std;
class Box {
public:
double length;
// 创建内部
// double getLen(double len){ //类成员函数
// length = len;
// cout<<"The length is "<< length <<endl;
// return length;
// }
// Must state here if use externel member function
double getLen(double len);
};
// 外部定义类成员函数,其中::表示范围解析符
double Box::getLen(double len) {
length = 2 * len;
cout << "The length is " << length << endl;
return length;
}
int main() {
Box a; // 创建一个对象a
double len = 1.5;
a.getLen(len); //调用成员函数
return 0;
}
//output:
The length is 3
4、类修饰符
//类访问修饰符可以为每个成员进行权限的保护
//class Books{
//public: // 公有成员
//private: // 私有成员
//protected: // 受保护成员
//
//};
#include<iostream>
using namespace std;
typedef class Box {
private:
double width;
public:
double setWidth(double wid);
double height = 10;
protected: // protected和private相似,但是在其子类中可以访问
double length;
} Box;
这里的SubBox继承Box类,叫做子类,Box叫做父类,注意这里的继承是:而不是::
class SubBox : Box {
public:
void setLen(double len);
};
void SubBox::setLen(double len) {
length = len;
cout << "The length is " << length << endl;
}
double Box::setWidth(double wid) {
width = wid;
return width;
}
/*
1.public 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:public, protected, private
2.protected 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:protected, protected, private
3.private 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:private, private, private
*/
typedef class secretBox : private Box {
public:
int weight = 10;
} pBox;
int main() {
Box smallBox;
// double
// subBox.width; //这样的方法只能访问到height,需要使用函数去访问width;
cout << "The width is " << smallBox.setWidth(10) << endl;
SubBox littleBox;
littleBox.setLen(1.5);
pBox prBox;
// cout << prBox.height << endl; //报错
cout <<"The weight is "<< prBox.weight << endl;
return 0;
}
// output:
The width is 10
The length is 1.5
The weight is 10