1.
2.
静态属性
带构造函数的类
C++中对文件的操作
#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;
}