C++ oop

1.

#include <iostream>
using namespace std;
class Car
{
public:
void display()
{
cout << "This car's color is black!" << endl;
}
private:
int price;
string color;
};
int main(int argc,char **argv)
{
Car c;
c.display();

Car *c2 = new Car;
c2->display();
return 0;
}

#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("hello.txt");
string s;
ifs >> s;
string st;
ifs >> st;
cout << s <<", " << st <<endl;
ifs.close();
return 0;
}



2.

#include <iostream>
using namespace std;
class Car
{
public:
void display();
void init(string,string);
private:
string name;
string color;
};
void Car::init(string name,string color)
{
this->name = name;
this->color = color;
}
void Car::display()
{
cout << "The car name is : " << name << ", " << "Color is : " << color << endl;
}
int main(int argc,char **argv)
{
Car *c = new Car;
c->init("Fold","Black");
c->display();
}


静态属性

class Car {
public:
static int id;
...
};
int Car::id = 10;

int main(){
Car::id = 12; //使用
}

静态函数
class Car {
public:
static int id;
static void display();
};
int Car:: id = 22;
void Car::display()
{
cout << "id is : " << id << endl;
}

int main()
{
Car::id = 10;
Car::display();
}


带构造函数的类

#include <iostream>
using namespace std;
class Car
{
public:
Car(string,string); //declare constructor
void display();
private:
string name;
string color;
};

Car::Car(string name,string color) //definition constructor
{
this->name = name;
this->color = color;
}

void Car::display()
{
cout << "Name is : " << name << ", " << "Color is : " << color << endl;
}

int main(int argc,char **argv)
{
Car *c = new Car("Toyota","Black");
c->display();
}


C++中对文件的操作

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ofstream ofs("hello.txt");
ofs << "hello linux" << endl;
ofs << "C++ is very good!" << endl;
ofs.close();
return 0;
}

#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("hello.txt");
string s;
ifs >> s;
string st;
ifs >> st;
cout << s <<", " << st <<endl;
ifs.close();
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值