1.以上是对本章知识的大致梳理,下面通过我自己在编程中遇到的问题再次总结。
- 私有成员必须通过get()函数访问吗?能不能直接调用?
- 私有成员必须通过公共函数接口去访问,比如设置set()修改成员内容,利用get()取值。
-
另外还可以利用友元访问#include<iostream>
using namespace std;
class B;
class A
{
friend B;
public:
A(){}
~A(){}
private:
void print(){cout << "It's in A class" << endl;}
};
class B
{
public:
B(){}
~B(){}
void test(){a.print();}//A的私有成员函数直接调用
private:
A a;
};
int main()
{
B b;
b.test();
system("pause");
return 0;
}
-
构造函数()要不要写出参数?
- 在类中构造函数必须要有形参,可以给定默认值参数,也可以不给。对象初始化可以通过对象.(参数),也可以通过对象.set()修改默认值。
-
使用内联示例:
View Code
1 #include<iostream> 2 using namespace std; 3 class Dog{ 4 public: 5 Dog(int initage=0,int initweight=0); 6 ~Dog(); 7 int GetAge(){ 8 return age; 9 }//内联隐式函数 10 void setage(int ages){ 11 age=ages; 12 } 13 int getweight(){ 14 return weight; 15 } 16 void setweight(int weights){ 17 weight=weights; 18 } 19 20 private: 21 int age;int weight; 22 }; 23 Dog::Dog(int initage,int initweight){ 24 age=initage; 25 weight=initweight; 26 } 27 Dog::~Dog(){ 28 } 29 int main(){ 30 Dog a; 31 cout<<a.getweight(); 32 return 0; 33 }