第二周 类和对象基础 - PKU[课程作业]程序设计与算法(三)C++面向对象程序设计

001:编程填空:学生信息处理 程序
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <cstdlib>
using namespace std;

class Student {
	private:
		char name[20];
		int age, ID;
		int score[4];
		double avg;
	public:
		void input()
		{
			cin.getline(name,20,',');
			char c;
			cin >> age >> c >> ID >> c;
			cin >> score[0] >> c >> score[1] >> c >>  score[2] >> c >> score[3];
		} 
		void calculate()
		{
			avg = (double)(score[0]+score[1]+score[2]+score[3])/4;
		}
		void output()
		{
			cout << name << "," << age << "," << ID << "," << avg << endl;
		} 
};

int main() {
	Student student;        // 定义类的对象
	student.input();        // 输入数据
	student.calculate();    // 计算平均成绩
	student.output();       // 输出数据
}
002:奇怪的类复
#include <iostream>
using namespace std;
class Sample {
public:
	int v;
	Sample( int n = 0 ){
//		cout << "[1]" << endl; 
		v = n;
	}
	Sample( const Sample & S ){
//		cout << "[2]" << endl;
		v = S.v+2;
	}
};
void PrintAndDouble(Sample o)
{
	cout << o.v;
	cout << endl;
}
int main()
{
	Sample a(5);
	Sample b = a;
	PrintAndDouble(b);
	Sample c = 20;
	PrintAndDouble(c);
	Sample d;
	d = a;
	cout << d.v;
	return 0;
}
题目中多次调用复制构造函数,每次复制构造函数都会生成临时变量。
由于复制构造函数的声明中,参数是Sample &,不是常量引用,因为c++编译器的一个关于语义的限制。
如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,
并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,
由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,
因此c++编译器加入了临时变量不能作为非const引用的这个语义限制
citation: https://blog.csdn.net/qq_36667170/article/details/79764449


003:超简单的复数类
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
    double r,i;
public:
    void Print() {
        cout << r << "+" << i << "i" << endl;
    }
    Complex & operator=( const string & s ){
		int pos = s.find("+", 0);
		string sTmp = s.substr(0, pos);
    	r = atof(sTmp.c_str());
    	sTmp = s.substr(pos+1, s.length()-pos-2);
    	i = atof(sTmp.c_str());
    	return *this;
	}
};
int main() {
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}

004:哪来的输出
#include <iostream>
using namespace std;
class A {
	public:
		int i;
		A(int x) { i = x; }
		~A() { cout << i << endl; } 
};
int main()
{
	A a(1);
	A * pa = new A(2);
	delete pa;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/momo_flamboyant/article/details/79808133