[C++学习]C++常见问题

1,一个函数可以既是虚函数又是内联函数吗?

不能,虚函数意味在运行期确定函数的调用地址,内联函数如同宏的用法一样,相当于在编译期把调用内联的地方加上了函数实现的代码。前者是动态的,后者是静态的。另外,即使编译器通过了编译,那么函数也不可能是内联的


2,C++类的大小

#include <iostream>
 using namespace std;
 class A{};
 class B
 {
     int b;
     char c;
 };
 class C
 {
     int c1;    
     static int c2;
 };
 int C::c2 = 1;
 class D:public C,public B{
     int d;
 }; 
 int main()
 {
     cout<<"sizeof(A)="<<sizeof(A)<<endl;
     cout<<"sizeof(B)="<<sizeof(B)<<endl;
     cout<<"sizeof(C)="<<sizeof(C)<<endl;
     cout<<"sizeof(D)="<<sizeof(D)<<endl;
     return 0;
 }

 运行结果为1 8 4 16 对于类A来说,虽然A是一个空类,但为了便于空类进行实例化,编译器往往会给它分配一个字节,这样A实例化后便在内存中有了一个独一无二的地址.

对于类B,B的大小应为sizeof(int)+sizeof(char)=5,但是考虑内存对齐,B的大小应为8.对于类C,类的静态成员变量被放在全局区,和类的普通成员并没有放在一块。类的静态成员被声明后就已存在,而非静态成员只有类被实例化后才存在。所以C的大小为sizeof(int)=4。D的大小为B+C的大小+自身数据成员的大小,一共为16.


3,String类

#include <stdio.h> 
#include <iostream>
#include <string.h>
#include <stdlib.h>

class String{
public:
	String(const char*str = NULL);
	String(const String &another);
	~String();
	String& operator =(const String &rhs);
private:
	char* m_data;
};


String::String(const char*str)
{
	if(str == NULL)
	{
		m_data = new char[1];
		m_data = '\0';
	}
	else
	{
		m_data = new char[strlen(str)+1];
		strcpy(m_data,str);
	}
}

String::String(const String&another)
{
	m_data = new char[strlen(another.m_data)+1];
	strcpy(m_data,another.m_data);
}

String & String::operator=(const String &rhs)
{
	if(this ==&rhs)
	{
		return *this;
	}
	delete []m_data;
	m_data = new char[sizeof(rhs.m_data)+1];
	strcpy(m_data,rhs.m_data);
	return*this;
}

String::~String()
{
	delete []m_data;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值