大題:二級C++回顧(二)

1.基礎操作題


#include <iostream>
using namespace std;
class AAA {
    int a[10]; int n; 
//ERROR **********found**********
public: 
    AAA(int aa[], int nn): n(nn) {
        //ERROR **********found**********
        for(int i=0; i<n; i++) a[i] = aa[i];
    } 
    int Geta(int i) {return a[i];}
}; 
int main() {
    int a[6]={2,5,8,10,15,20};
    AAA x(a,6);
    int sum=0; 
    //ERROR **********found**********
    for(int i=0; i<6; i++) sum+=x.Geta(i);
	cout<<"sum="<<sum<<endl; 
    return 0;
} 

2. 簡單應用題


// proj2.cpp
#include <iostream>
using namespace std;

const int MAXNUM = 100;

class Set {
private:
	int num;			// 元素個數
	char setdata[MAXNUM];		// 字符數組,用於存儲集合元素
public:
	Set(char *s); 			// 構造函數,用字符串s構造一個集合對象
	bool InSet(char c);		// 判斷一個字符c是否在集合中,若在,返回true,否則返回false
	void Print() const;         	// 輸出集合中所有元素
};

Set::Set(char *s)
{
	num = 0;
	while (*s){
//**********found**********
    if (!InSet(*s))         // TODO: 添加代碼,測試元素在集合中不存在
//**********found**********
	    setdata[num++]=*s;    // TODO: 添加一條語句,加入元素至集合中
		s++;
	}
}

bool Set::InSet(char c)
{
	for (int i = 0; i < num; i++)
//**********found**********
	  if (c==setdata[i])    // TODO: 添加代碼,測試元素c是否與集合中某元素相同
//**********found**********
	     return true;        // TODO: 添加一條語句,進行相應處理

	return false;
}

void Set::Print() const
{
	cout << "Set elements: " << endl;
	for(int i = 0; i < num; i++)
		cout << setdata[i] << ' ';
	cout << endl;
}

int main()
{
	char s[MAXNUM];
	cin.getline(s, MAXNUM-1);		// 從標準輸入中讀入一行
	Set setobj(s);				// 構造對象setobj
	setobj.Print();				// 顯示對象setobj中內容
	return 0;
}

 

 3.綜合應用題

#include "MiniComplex.h"
#include<fstream>

MiniComplex::MiniComplex(double real, double imag){  realPart = real;	imagPart = imag;}

MiniComplex MiniComplex::operator+ (const MiniComplex& otherComplex) const
{
//********333********
	MiniComplex sum;
	sum.imagPart = this->imagPart + otherComplex.imagPart;
	sum.realPart = this->realPart + otherComplex.realPart;
	return sum;


//********666********
}  

int main()
{
  void writeToFile(char *);
  MiniComplex num1(23,34), num2(56,35);
  cout<<"Initial Value of Num1 = "<<num1<<"\nInitial Value of Num2 = "<<num2<<endl;
  cout<<num1<<" + "<<num2<<" = "<<num1 + num2<<endl;//使用重載的加號運算符
  writeToFile("");
  return 0;
}

void writeToFile(char *path)
{
	char filename[30];
	strcpy(filename,path);
	strcat(filename,"out.dat");
	ofstream fout(filename);

	MiniComplex num1(88,96), num2(-3,25);
	fout<<"Initial Value of Num1 = "<<num1<<"\nInitial Value of Num2 = "<<num2<<endl;
	fout<<num1<<" + "<<num2<<" = "<<num1 + num2<<endl;
	fout.close();
	

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章