用C、c++、python、php分别写同一个结构体
时间: 2023-07-10 16:38:17 浏览: 70
以下是用 C、C++、Python、PHP 分别写同一个结构体的示例:
在 C 中:
```c
#include <stdio.h>
struct person {
char name[20];
int age;
};
int main() {
struct person p;
printf("Enter name: ");
scanf("%s", p.name);
printf("Enter age: ");
scanf("%d", &p.age);
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
return 0;
}
```
在 C++ 中:
```cpp
#include <iostream>
#include <string>
using namespace std;
struct person {
string name;
int age;
};
int main() {
person p;
cout << "Enter name: ";
cin >> p.name;
cout << "Enter age: ";
cin >> p.age;
cout << "Name: " << p.name << endl;
cout << "Age: " << p.age << endl;
return 0;
}
```
在 Python 中:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person(input("Enter name: "), int(input("Enter age: ")))
print("Name: ", p.name)
print("Age: ", p.age)
```
在 PHP 中:
```php
<?php
class Person {
public $name;
public $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$p = new Person(readline("Enter name: "), readline("Enter age: "));
echo "Name: " . $p->name . "\n";
echo "Age: " . $p->age . "\n";
?>
```
阅读全文