类与对象(上)
C语言中,结构体中只能定义变量,不能定义函数。
相关代码:
#include <stdio.h>
{
int a;
double b;
char c;
};
C++中,结构体既可以定义变量,又可以定义函数。
相关代码:
#include <iostream>
using namespace std:
{
int a;
double b;
char c;
void fun()
{
printf("This is fun().\n");
}
};
类的定义
class className
{
//类体:由成员变量和成员函数组成
};//一定要注意后面有分号
class为类的关键字,className为类的名字,{}为类的主体,注意类定义结束时后面有分号。
类的两种定义方式:
1.声明和定义全部放在主体中,需要注意的是:成员函数如果在类中定义,编译器可能会将其当成内联函数处理。
相关代码:
#include <iostream>
using namespace std;
class CGoods
{
public:
void Register(char* name,int count,int price) //注册商品
{
strcpy(m_name , name);
m_count = count;
m_price = price;
m_total_price = m_count * m_price;
}
void GetName(char* name) //获取名字
{
strcpy(name , m_name);
}
void GetCount()
{
return m_count;
}
void GetPrice()
{
return m_price;
}
void GetTotalPrice()
{
return m_total_price;
}
private:
char m_name[10];
int m_count;
float m_price;
float m_total_price;
};
void main()
{
CGoods c; //实例化对象
c.Register("C++" , 8 , 60);
char name[10];
c.GetName(name);
cout<<"name = "<<name<<endl;
}
2.声明放在.h文件中,类的定义放在.cpp文件中。
//类的申明
Test.h
class CGoods
{
public:
void Register(char* name,int count,int price);
void GetName(char* name);
int Getcount();
float Getprice();
float GetTotalPrice();
private:
{
char m_name[10];
int m_count;
float m_price;
float m_totalprice;
};
//类的定义
Test.cpp
#include "Test.h"
#include <iostream>
void CGoods:: Register(char* name,int count,int price)
{
strcpy(m_name,name);
m_count = count;
m_price = price;
m_total_price = m_count * m_price;
}
void CGoods:: GetName(char* name) //获取名字
{
strcpy(name , m_name);
}
void CGoods:: GetCount()
{
return m_count;
}
void CGoods:: GetPrice()
{
return m_price;
}
void CGoods:: GetTotalPrice()
{
return m_total_price;
}
TestMain.cpp
void main()
{
CGoods c;
c.Register("C",6,50);
}
访问限定符
1.public (公有)
2.protected (保护)
3.private (私有)
public(公有)修饰的成员在类外可以直接被访问;
protected(保护)和private(私有)修饰的成员在类外不能直接被访问;
class的默认访问权限为private(私有),struct的默认访问权限为public(公有)
类的作用域
类定义了 一个新的作用域,类的所有成员都在类的作用域中;在类体外定义的成员,需要使用::作用域解析符指明成员属于哪一个类域。
this指针
1.this指针的类型:类类型* const (Test *const this)
2.只能在“成员函数”的内部使用
3.this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参;所以对象中不存储this指针
4.this指针的创建——this指针在成员函数的开始执行前构造的,在成员的执行结束后清除。
this指针中一丢丢的总结:
对于一个类的实例来说,
你可以看到它的成员函数、成员变量,
但是实例本身是看不到地;
this是一个指针,
它时时刻刻指向你这个实例本身。