2016-12-22 5 views
1

プログラムは、この特定の方法でグレード1の等式を解決する必要があります。コードの理解を深めるために、コンストラクタとデストラクタの出力メッセージを使用しなければなりませんでした。今コンストラクタのコピー

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

class Ec { 
public: float a, b; //equation's parameters 
public: 
    Ec() {float x, y; cout <<"a= "; cin >> x; cout << "b= "; 
      cin >> y; a = x; b = y; cout << "void constr\n";}; 
    Ec(float x, float y) { a = x; b = y; cout << "param constr\n"; } 
    ~Ec() { cout << "destr\n"; } 
    Ec(Ec &z) { a = z.a; b = z.b; cout << "cpy constr\n"; } 

friend float half1(Ec); //function to return a/2 
friend float half2(Ec); //function to return b/2 
friend float sol1(Ec); //function to return the solution for the standard eq 
friend float sol2(Ec); //function to return the sol for the /2 param eq 
}; 

float half1(Ec ec1) { return (ec1.a/2);} 
float half2(Ec ec1) { return (ec1.b/2); } 

float sol1(Ec ec1) { float x; return x = -ec1.b/ec1.a; } 
float sol2(Ec ec1) { float x2; return x2 = -half2(ec1)/half1(ec1); } 

int main() 
{ 
    int x, y; 
     cout << "a= "; 
     cin >> x; 
     cout << "b= "; 
     cin >> y; 
     Ec ec1; 
     Ec ec2(x, y); 
     Ec ec3 = ec1; 
//the couts display for ex:" ec 2x+1=0 has sol -0.5" 
     cout << "ec " << ec1.a << "x+ " << ec1.b << "=0 has sol " << sol1(ec1) << endl; 
     cout << "ec " << ec2.a << "x+ " << ec2.b << "=0 has sol " << sol1(ec2) << endl; 
     cout << "ec " << ec3.a << "x+ " << ec3.b << "=0 has sol " << sol1(ec3) << endl; 

     cout << "ec halved " << half1(ec1) << "x+ " << half2(ec1) << "=0 has sol " << sol2(ec1) << endl; 
     cout << "ec halved " << half1(ec2) << "x+ " << half2(ec2) << "=0 has sol " << sol2(ec2) << endl; 
     cout << "ec halved " << half1(ec3) << "x+ " << half2(ec3) << "=0 has sol " << sol2(ec3) << endl; 
    } 
    return 0; 
} 

、私は(EC3のための)最初のCPYコンストラクタの後に別のCPYコンストラクタがデストラクタその後、呼び出された理由を理解するトラブルを持っています。それは何ですか?

+0

ようこそ引数を渡したい場合。 [The Tour](http://stackoverflow.com/tour)を読み、[ヘルプセンター](http://stackoverflow.com/help/asking)の資料を参考にしてください。ここに聞いてください。 –

+1

あなたの関数は値で 'Ec'を受け入れます。そのため、コピーは渡されます。 – AndyG

答えて

3

あなたの機能が、これらは、各機能の終了時に破壊されている機能のローカルコピーを行います値

float half1(Ec ec1) { return (ec1.a/2);} 
      ^

によってEcオブジェクトを取ります。

あなたは、これらのコピーを作成することを避けるため、スタックオーバーフローをconst参照によって

float half1(Ec const& ec1) { return (ec1.a/2);} 
      ^
関連する問題