使用函数输出结构值

时间:2014-03-14 13:56:01

标签: c++ function data-structures

您好我刚刚开始尝试结构。我尝试运行一个非常基本的程序,其中一个结构(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)
{

    //      
}

3 个答案:

答案 0 :(得分:1)

这可能有效

 #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;
    //      
}

答案 1 :(得分:1)

许多可能性之一是

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

重载运算符&lt;&lt;

但是,如果输出操作的逻辑更复杂,您可以在类中定义operator<<( std::ostream& oot, pointType const& p)。当您想要在写入输出流时执行其他操作时,或者当要打印的内容不是简单的内置类型时,这非常有用,因此您无法直接编写std::cout << point.x。也许您还希望使用不同的 区域设置 facet 来打印特定类型的变量,这样您也可以 imbue 重载运算符内的流。

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;
}

答案 2 :(得分: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>