C++学習ノート(十一)--対象
2458 ワード
1構造体からクラスへ
2一般的にクラスの定義と実装は別々に書く
08time.h
08time.cpp
// .cpp : 。
//
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Ps //C++ public
{
private:
string name;
int age;
public:
Ps():name("xiaoming"),age(17){}
Ps(const char *name,int age):name(name),age(age){}
void show()
{
cout << name <<" " << age <<endl;
}
};
class Ps2
{
private:
string name;
int age;
public:
Ps2():name("xiaoming"),age(17){}
Ps2(const char *name,int age):name(name),age(age){}
void show()
{
cout << name <<" " << age <<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Ps s;
s.show();
//cout << s.age << endl;
Ps2 s2("daming",20);
s2.show();
system("pause");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
struct Ps
{
string name;
int age;
void show()
{
cout << " " << name << ", " << age <<endl;
}
}; // new types may not be defined in a return type
class Pc
{
string name;
int age;
public:
Pc(const char *n,int a){name=n;age=a;}
void show()
{
cout << " " << name << ", " << age <<endl;
}
};//
int main()
{
Ps a = {" ",18}; //
Pc c(" ",20); //
a.show();
c.show();
}
2一般的にクラスの定義と実装は別々に書く
08time.h
#ifndef TIME_H
#define TIME_H
class Time
{
int h,m,s;
public:
Time();
Time(int h,int m,int s);
void tick();
void show();
};
#endif
//
//cpp
08time.cpp
#include <iostream>
#include <iomanip>
#include "08time.h"
using namespace std;
Time::Time(){h=m=s=0;}//Time::
Time::Time(int h,int m,int s)
{
Time::h=h; Time::m=m;Time::s=s;
}
void Time::tick()
{
if(++s >= 60)
{
s = 0;
if(++m >= 60)
{
m = 0;
if(++h >= 24)
{
h=0;
}
}
}
}
void Time::show()
{
cout << setfill('0') <<setw(2) << h << ':' << setw(2)
<< m << ':' << setw(2) << s << endl;
}
int main()
{
Time t(10,56,00);
while(1)
{
sleep(1);
t.tick();
t.show();
}
}