【説明】
main関数内のクラスの動作に合わせて、クラスの実装部分を補足してコードを完成させてください。
このクラスには、このクラスのすべてのオブジェクトの数を記録するためのプライベート静的変数 count があります。main 関数は、さまざまなステートメントの後にオブジェクトの数を出力します。このクラスを正しく実装し、count がこのクラスのオブジェクトの数を正しく記録することを保証する場合のみ、クラスで正しい結果を出力することができます。
【入力】
入力はありません。
[出力]
main関数の出力が書き込まれました。
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int id;
static int count;
public:
/* 请在此处编写相关代码 */
static void InitCount(){
count=0;
}
Student(){
count++;
}
Student(int a){
//如果输入一个整数
id=a;
count++;
}
Student(const Student &stu){
//复制构造函数,构造一个对象,count+1
id=stu.id;
count++;
}
~Student(){
//析构完一个,count-1
count--;
}
friend void PrintCount();//用友元,可以直接访问对象的私有数据成员count
friend void Print(Student s);//可以直接访问私有成员s2.id,无需get,数据共享
/* 请在此处编写相关代码 */
};
int Student::count;
void PrintCount() {
cout << "Total " << Student::count << " students" << endl;
}
void Print(Student s) {
cout << "the id is " << s.id << endl;
}
int main() {
Student::InitCount();
Student s;
PrintCount();
Student s1(10);
Student s2(s1);
PrintCount();
Print(s2); // 调用拷贝构造函数,调用结束调用析构函数
PrintCount();
return 0;
}
[説明]
線分を表現するための Line クラスを宣言および実装します。Line クラスには以下が含まれます。
Point クラスのプライベート オブジェクト データ メンバーの start と end は、線分の 2 つの端点を表します。
セグメントのエンドポイントを指定されたパラメーターに設定するパラメーター化されたコンストラクター。
メンバー関数の傾きは、線分の傾きを計算します。
【入力】
点1(x1,y1)と点2(x2,y2)の座標を表す4つの数値を入力します。
【出力】
直線の傾きを出力します。
【入力例】
10 20 30 70
【出力例】
2.5
【ヒント】
Point クラスについては、「プログラムの基礎 - C++ を例に」の第 5 章の実験 1 を参照してください。
【出典】
『プログラミングの基礎 - Cを例に-』第6章の実験1。
#include <iostream>
#include <cmath>
using namespace std;
/* 请在此处分别编写Point类和Line类 */
class Line;//向前声明
class Point{
private:
double start;
double end;
public:
friend Line;//Line可以访问Point的私有成员了
Point(double &x,double &y){
start=x;
end=y;
}
};
class Line{
private:
double k;
public:
Line(const Point &x,const Point &y){
//复制构造函数
k=(y.end-x.end)/(y.start-x.start);//已知两点,计算斜率
}
double slope(){
//输出
return k;
}
};
/* 请在此处分别编写Point类和Line类 */
int main() {
double x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Point start(x1, y1);
Point end(x2, y2);
Line line(start, end);
cout << line.slope() << endl;
return 0;
}