对于C++对象的一些杂记,若存在错误,请各位赐教!
*****************************************
#include<iostream.h>
using namespace std;
编译错误:
Compiling...
C++类.CPP
D:/windows编程/C++类.CPP(2) : error C2871: 'std' : does not exist or is not a namespace
正确的使用:
#include<iostream>
using namespace std;
*****************************************
对象的使用:
申明对象
*****************************************
const int SIZE = 40;
class employee
{
private:
char name[SIZE];
public:
void set_name(char arg_name[SIZE])
{
strncpy(name, arg_name, SIZE);
}
void display_name(void)
{
cout << name;
}
};
void main(){
employee mechanic;
mechanic.set_name("lee");
mechanic.display_name();
}
********************************************
对employee的名字设定采用employee.set_name("John")
而使用employee.name="John"为wrong(其位于private中,若为name声明于public中这行可行)
可用指针对对象进行操作:
*********************************************
employee mechanic;
employee* ptrmechanic;
ptrmechanic = &mechanic;
ptrmechanic->set_name("John Doe");
*********************************************
反析构函数只有一个,对多次调用函数采用范围解析(类内编译器默认内联)
*********************************************
const int SIZE = 40;
class employee
{
private:
char name[SIZE];
public:
employee() //constructor
{
strncpy(name, "Unemployed", SIZE);
}
~employee() //destructor
{
}
void set_name(char[SIZE]); //function declarations only
void display_name(void);
};
// the :: is the scope resolution operator
void employee::set_name(char arg_name[SIZE])
{
strncpy(name, arg_name, SIZE);
}
void employee::display_name(void)
{
cout << name;
}
************************************************
在main于winmain中范围解析不能呼叫类的成员函数
use the dot operator or the member access operator for pointers(对此处有点歧义)
************************************************
#include<iostream>
using namespace std;
const int SIZE = 40;
class employee
{
private:
char name[SIZE];
public:
employee() //constructor
{
strncpy(name, "Unemployed", SIZE);
}
~employee() //destructor
{
}
void set_name(char[SIZE]); //function declarations only
void display_name(void);
};
// the :: is the scope resolution operator
void employee::set_name(char arg_name[SIZE])
{
strncpy(name, arg_name, SIZE);
}
void employee::display_name(void)
{
cout << name<<"/n";
}
void main(){
employee mechanic;
employee* ptrmechanic;
ptrmechanic = &mechanic;
ptrmechanic->set_name("John Doe");
ptrmechanic->display_name();
}
*****************************************
void main(){
employee mechanic;
mechanic.set_name("John Doe");
mechanic.display_name();
}也是正确的
*********************************************