C++继承与引用

 //test.hpp
#ifndef TEST_H
#define TEST_H

#ifndef TEST_API
#define TEST_API
#endif

#ifdef TEST_EXPORTS
#undef TEST_API
#define TEST_API __declspec(dllexport)
#endif
#ifdef TEST_IMPORTS
#undef TEST_API
#define TEST_API __declspec(dllimport)
#endif

namespace test {
class TEST_API test
{
public:
test();
virtual ~test()
{
}
virtual void print(char* str);
void operator<<(char* str);
char* name;
};
class TEST_API test1
{
private:
test* t;
public:
test1(test* tt);
virtual ~test1(){}
void print(char* str);
};
class TEST_API test2
{
private:
test& t;//如果这里使用了“&”,则实现中必须test2(test& tt):t(tt)这样初始化,并且得到的正确结果;
//如果没有“&”,怎样初始化print中都是调用test的print而不会出现test3
public:
test2(test& tt);
virtual ~test2(){}
void print(char* str);
};
extern TEST_API int test_int;
}
#endif


//test.cpp
#include "test.hpp"
#include <iostream>
namespace test {
TEST_API test::test()
{
name  = "[test]";
}
TEST_API  void test::print(char* str)
{
(*this)<<str;
}
TEST_API void test::operator<<( char* str)
{
std::cout<<str<<std::endl;
}
TEST_API test1::test1(test* tt)
{
this->t = tt;
std::cout<<t->name<<std::endl;
}
TEST_API void test1::print(char* str)
{
std::cout<<"In print: "<<t->name<<std::endl;
t->print(str);
}
TEST_API test2::test2(test& tt):t(tt)
{
//this->t = tt;
std::cout<<t.name<<std::endl;
}
TEST_API void test2::print(char* str)
{
std::cout<<"In print: "<<t.name<<std::endl;
t.print(str);
}
TEST_API int test_int = 101;
}


//test3.hpp
#include "test.hpp"

class test3 : public test::test
{
public:
test3():test()
{
std::cout<<"----"<<this->name<<std::endl;
name = "[test3]";
std::cout<<"----"<<this->name<<std::endl;
}
virtual void print(char * str)
{
std::cout<<str<<"   from test2"<<std::endl;
}
};
//T.cpp
#include <iostream>
#include "test.hpp"
#include "test3.hpp"
using namespace std;

int main(int argc, char *argv[])
{
cout<<"the number is : "<<test::test_int<<endl;
test::test *t = new test::test();
test::test1 t11(t);
t11.print("hello");
test3 t3;
test::test1 t13(&t3);
t13.print("world");
cout<<"-----------test2-------------"<<endl;
test::test2 t21(*t);
t21.print("hello 1");
test::test2 t23(t3);
t23.print("world 3");
return 0;
}
命令行:
cl /LD /MT /EHsc /D"TEST_EXPORTS" test.cpp
cl /MT /EHsc /D"TEST_IMPORTS" T.cpp /link test.lib
注意test2中变量t的类型定义为“test&”,那么实现中对t的初始化必须在“base/member List”中,如红色部分所示 。 而如果定义为“test t”,那么两种初始化方法没有区别(另一种为注释掉的this->t = tt),并且调用print函数得到的结果也是一样,只有“world 3”,而不是“world 3   from test2”。也就是说继承于test的test3中的print根本没有调用到,虽然此时name已经为“test3”。
难道这跟传值和传引用相关?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值