簡體   English   中英

使用函數輸出結構值

[英]using a function to output struct values

嗨,我剛剛開始嘗試結構。 我試着運行一個非常基本的程序,其中一個結構(x,y)中的兩個點由一個函數輸出。 我知道這是非常基本的,但我一直在努力,只是想不出來。 任何幫助將不勝感激!

using namespace std;

void printPoint(const pointType& point); 

struct pointType 
{
    int x;
    int y;
}

int _tmain(int argc, _TCHAR* argv[])
{
    struct pointType pos1;
    pos1.x = 10;
    pos1.y = 15;

    printPoint();


    system("pause");
    return 0;
}

void printPoint(const pointType& point)
{

    //      
}

這可能會奏效

 #include <iostream>

using namespace std;

struct pointType
{
    int x;
    int y;
};

void printPoint(const pointType& point); 


int main(int argc, char** argv)
{
    struct pointType pos1;
    pos1.x = 10;
    pos1.y = 15;

    printPoint(pos1);


    //system("pause");
    return 0;
}

void printPoint(const pointType& point)
{
    cout << point.x << '\t' << point.y << endl;
    //      
}

許多可能性之一是

void printPoint(const pointType& point){
  std::cout << "x:" << point.x << ", y:" << point.y << std::endl;
}

重載運算符<<

但是,如果輸出操作的邏輯更復雜,您可以在類中定義operator<<( std::ostream& oot, pointType const& p) 當你想要在寫入輸出流時做一些額外的事情,或者當打印的內容不是簡單的內置類型時,這很有用,所以你不能直接寫std::cout << point.x . 也許您還希望使用不同的區域設置構面來打印特定類型的變量,因此您還可以在重載運算符內部填充流。

struct pointType {
  int x;
  int y;
  friend std::ostream& operator<<( std::ostream &out, pointType const& p);
    ^
  // needed when access to private representation is required,
  // here it is not the case, friend specifier not required
}

std::ostream& operator<<( std::ostream &out, pointType const& p) {
  //.. do something maybe
  out << "x:" << point.x << ", y:" << point.y << std::endl;
  //.. maybe something more
  return out;
}

所以現在你可以簡單地以通常的方式使用輸出流:

int main() {
  pointType p;
  std::cout << p;
  return 0;
}

您應該在函數聲明之前定義結構,或者函數聲明應該使用詳細的名稱,該名稱是具有關鍵字struct的結構的名稱

struct pointType {
int x;
int y;
};

void printPoint(const pointType& point); 

要么

void printPoint(const struct pointType& point); 

struct pointType {
int x;
int y;
};

否則,編譯器將不知道pointType在函數聲明中的含義。

結構定義應以分號結束

struct pointType {
int x;
int y;
};

在這個聲明中

struct pointType pos1;

沒有必要指定關鍵字struct,你可以寫得更簡單

pointType pos1;

您也可以通過以下方式初始化對象

struct pointType pos1 =  { 10, 15 };

函數調用應該有一個參數,因為它被聲明為有參數。 而不是

printPoint();

printPoint( pos1 );

函數本身可以采用以下方式

void printPoint(const pointType& point)
{
   std::cout << "x = " << point.x << ", y = " << point,y << std::endl;
}

不要忘記包含標題<iostream>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM